<?php
declare (strict_types=1);

use think\facade\Cache;

/**
 * @title 检查用户的权限
 * @param string $url thinkphp的访问地址(不区分大小写)
 * @param int $role_id 角色的id,不传默认获取当前登录用户的角色id
 * @return bool
 * *@author wanghao
 */
function check_auth(string $url, int $role_id = 0): bool
{
    //获取当前登录的用户
    $AdminUserService = app\common\service\AdminUserService::ins();
    if ($role_id == 0) {
        $user_info = $AdminUserService->getUserInfo();
        if (!$user_info) {
            return false;
        }
        $role_id = $user_info['role_id'];
    }
    $AdminMenuService = app\common\service\AdminMenuService::ins();
    return $AdminMenuService->checkAdminAuth($role_id, strtolower($url));
}

/**
 * @title 导出excel
 * @param string $filename 保存的文件名称
 * @param array $tileArray 字段名称注释,一维数组:['唯一id','姓名','手机号']
 * @param array $dataArray 需要导出的数据,二维数组:[['1','王浩','15171501063'],['2','张三','15171501064']]
 * @return \think\Response
 * */
function export_excel(string $filename, array $tileArray = [], array $dataArray = [])
{
    $filename = $filename . date('Y-m-d H:i:s');
    ini_set('memory_limit', '512M');
    ini_set('max_execution_time', '0');
    ob_start();
    header("Content-Type: text/csv");
    header("Content-Disposition:filename={$filename}.csv");
    $fp = fopen('php://output', 'w');
    fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))
    fputcsv($fp, $tileArray);
    $index = 0;
    foreach ($dataArray as $item) {
        if ($index == 1000) {
            $index = 0;
            ob_flush();
            flush();
        }
        $index++;
        fputcsv($fp, $item);
    }
    ob_flush();
    flush();
    ob_end_clean();
    return response('', 200, ['Content-Type' => 'text/csv;charset=UTF-8']);
}

/**
 * @title 获取一个随机的字符串
 * @param int $len
 * @return string
 * @author wanghao
 */
function rand_str(int $len = 5): string
{
    $repeat_len = $len > 10 ? 10 : $len;
    $str = str_repeat('QWERTYUIOPASDFGHJKLZXCVBNM1234567890', $repeat_len);
    return strtolower(substr(str_shuffle($str), mt_rand(0, strlen($str) - 11), $len));
}

/**
 * @title 隐藏字符串重要信息
 * @param string $str 需要隐藏信息的字符串
 * @param int $left 左边保留字符串个数
 * @param int $right 右边保留字符串个数
 * @param string $input 替换的字符串
 * @return string
 * */
function hide_info(string $str, int $left = 2, int $right = 2, string $input = '*'): string
{
    $len = mb_strlen($str, 'utf8');
    if (($left + $right) >= $len) {
        return $str;
    }
    if ($right > 0) {
        return mb_substr($str, 0, $left, 'utf-8') . str_repeat($input, $len - $left - $right) . mb_substr($str, -$right, null, 'utf-8');
    }
    return mb_substr($str, 0, $left, 'utf-8') . str_repeat($input, $len - $left - $right);
}

/**
 * @title 插入日志
 * @param string $group 日志分组
 * @param string $info 日志内容
 * @param string $level 日志级别 默认为info 可选 info/warn/error
 * @return bool
 */
function set_log(string $group, string $info, string $level = 'info'): bool
{
    if (!in_array($level, ['info', 'warn', 'error'])) {
        $level = 'info';
    }
    get_logger($group)->$level($info);
    return true;
}

/**
 * @title 获取模块日志handle
 * @param string $name 日志模块
 * @return object
 */
function get_logger(string $name): object
{
    static $loggerHandle = [];
    if (empty($loggerHandle)) {
        XLogKit::outLevel(7);
        $prj_name = isset($_SERVER["PRJ_NAME"]) ? $_SERVER["PRJ_NAME"] : 'not-know-prj';
        XLogKit::setApp($prj_name);
        $traceid = isset($_SERVER["HTTP_TRACEID"]) ? $_SERVER['HTTP_TRACEID'] : uniqid();
        XLogKit::setTraceId($traceid);
    }

    if (!isset($loggerHandle[$name])) {
        $logger = XLogKit::logger($name);
        $loggerHandle[$name] = $logger;
        return $logger;
    }
    return $loggerHandle[$name];
}

/**
 * @title 获取当前系统访问的url
 * @param int $type 1获取不带协议的连接,其他获取带协议的连接
 * @return string
 * */
function get_host(int $type = 0): string
{
    switch ($type) {
        case 1:
            $http_type = '//';
            break;
        default:
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
    }
    $url = $http_type . getenv('HTTP_HOST');
    return $url;
}

/**
 * @title 获取上传的对象
 * @return object 上传的对象
 * */
function upload_obj(): object
{
    static $obj = null;
    if (is_null($obj)) {
        $conf = config('system.upload');
        switch ($conf['type']) {
            case 'local':
                $obj = new app\common\library\upload\driver\Local();
                break;
            case 'ali_oss':
                $obj = new app\common\library\upload\driver\AliOss();
                break;
        }
    }
    return $obj;
}

/*
 * @title 数据请求
 * @param string $url 需要解密的数据
 * @param string $data 请求的数据,数组请使用http_build_query处理后传入
 * @param string $method 请求的类型
 * @param array $headers 请求的头信息
 * @param int $timeoutMs 超时时间,毫秒
 * @return array http状态和结果
 * */
function request_data(string $url, string $data = '', string $method = 'GET', array $headers = [], int $timeout_ms = 3000) :array
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, $timeout_ms);
    $https = substr($url, 0, 5) == 'https' ? true : false;
    if ($https) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    if ($method === 'GET') {
        curl_setopt($ch, CURLOPT_HTTPGET, true); //设置以GET方式发送
        if (!empty($data)) {
            $url = $url . '?' . $data;
        }
        curl_setopt($ch, CURLOPT_URL, $url);
    } else if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true); //设置以POST方式发送
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    $output = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ['code' => $code, 'output' => $output];
}

/**
 * @title 获取一个随机的字符串,用来更新前端js,css代码之后,更新缓存的
 * @return string
 * */
function cache_str(): string
{
    $key = config('app.sys_static_key');
    $rand_str = Cache::store('redis')->get((string)$key);
    if ($rand_str) {
        return $rand_str;
    }
    return '';
}

/*
 * @title 获取当前访问的菜单地址
 * */
function menu_url()
{
    $url = strtolower(trim(request()->baseUrl(), '/'));
    $suffix = config('route.url_html_suffix');
    if (empty($suffix)) {
        return $url;
    }
    return explode('.', $url)[0];
}

